import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_yn_goods/config/app_translations.dart';
import 'package:flutter_yn_goods/utils/loading/loading_utils.dart';
import 'package:flutter_yn_goods/utils/log/utils_log.dart';
import 'package:flutter_yn_goods/widgets/image/auto_image.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'main_logic.dart';

class MainPage extends StatelessWidget {
  final logic = Get.put(MainLogic());

  @override
  Widget build(BuildContext context) {
    return  PopScope(
      canPop: false,
      onPopInvoked: (bool? didPop) {
        if (didPop == true) {
          return;
        }
        int now = DateTime.now().millisecondsSinceEpoch;
        if (now - logic.lastPopTime > 3000) {
          logic.lastPopTime = now;
          LoadingUtils.showToast(LocaleKeys.initializing.tr);
          clog('再次点击返回将退出app');
        } else {
          logic.lastPopTime = 0;
          SystemChannels.platform.invokeMethod('SystemNavigator.pop');
        }
      },
      child: GetBuilder<MainLogic>(
        builder: (logic) {
          return _buildMain();
        },
      ),
    );
  }

  Widget _buildMain() {
    return Scaffold(
      body: _buildPageView(),
      bottomNavigationBar: Obx(() {
        return BottomNavigationBar(
          backgroundColor: Colors.black,
          currentIndex: logic.currentIndex.value,
          onTap: logic.selectIndex,
          showSelectedLabels: false,
          showUnselectedLabels: false,
          type: BottomNavigationBarType.fixed,
          elevation: 0.0,
          enableFeedback: false,
          items: logic.pages.map((e) {
            return BottomNavigationBarItem(
              label: "",
              icon: Column(
                children: [AutoImage(e.iconName, width: 24.w)],
              ),
              activeIcon: Column(
                children: [
                  AutoImage(e.activeIconName, width: 24.w),
                  4.w.verticalSpace,
                  Text(
                    e.name,
                    style: TextStyle(fontSize: 10.sp, color: Colors.white),
                  ),
                ],
              ),
            );
          }).toList(),
        );
      }),
    );
  }

  Widget _buildPageView() {
    return PageView.builder(
      controller: logic.pageController,
      physics: const NeverScrollableScrollPhysics(),
      itemBuilder: (BuildContext context, int index) {
        return logic.pages[index].page;
      },
    );
  }
}


